using System;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace AspAlliance.SimpleCms
{
    class ContentPage : CmsPageBase, IRequiresSessionState
    {
        private string _pageTitle;
        private HtmlMeta _description;
        private HtmlMeta _keywords;
        private string _masterPage;

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            CmsPage pageData;

            try
            {
                pageData = CmsPage.SelectByUrl(Request.AppRelativeCurrentExecutionFilePath, Cache);
            }
            catch (SqlException ex)
            {
                throw new HttpException(404, Resources.ErrorMessage404, ex);
            }

            AppRelativeVirtualPath = pageData.Url;
            _masterPage = string.IsNullOrEmpty(pageData.MasterPage) ? CmsConfig.MasterPage : pageData.MasterPage;

            try
            {
                if (System.IO.File.Exists(Server.MapPath(_masterPage)))
                {
                    MasterPageFile = _masterPage;
                }
                else
                {
                    throw new CmsConfigException(new CmsConfigException(), ExceptionType.MasterPage);
                }
            }
            catch (CmsConfigException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CmsConfigException(ex, ExceptionType.Other);
            }

            if (!string.IsNullOrEmpty(CmsConfig.Theme))
            {
                this.Theme = CmsConfig.Theme;
            }

            base.AddContentTemplate(Resources.DefaultContentPlaceHolder, new CmsContent(pageData.ContentText));
            _pageTitle = Server.HtmlEncode(pageData.Title);

            _description = new HtmlMeta();
            _description.Name = "Description";
            _description.Attributes["content"] = Server.HtmlEncode(pageData.Description);

            _keywords = new HtmlMeta();
            _keywords.Name = "Keywords";
            _keywords.Attributes["content"] = Server.HtmlEncode(pageData.Keywords);

        }
        protected override void Render(HtmlTextWriter writer)
        {
            this.Title = _pageTitle;

            // Find the <head> and put Meta Data in it
            foreach (Control eachControl in Master.Controls)
            {
                if (eachControl.GetType() == typeof(HtmlHead))
                {
                    eachControl.Controls.Add(_description);
                    eachControl.Controls.Add(_keywords);
                }
            }
            base.Render(writer);
        }
    }
}
